package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.dto.AdminDto;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.IAdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import sun.security.krb5.internal.crypto.DesCbcMd5EType;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-06-19
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {

    @Override
    public ResponseResult login(AdminDto dto) {
//        判断账户是否为空
        if (dto == null || StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
//        查询账户信息
        LambdaQueryWrapper<AdUser> query = new LambdaQueryWrapper<>();
        query.eq(AdUser::getName,dto.getName());
        AdUser one = this.getOne(query);
//        判断账户信息是否存在
        if (one == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
//        获取盐并md5加密判断密码是否正确
        String salt = one.getSalt();
        String password = dto.getPassword()+salt;
        String s = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!one.getPassword().equals(s)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
//        创建token
        Map<String,Object> userMap = new HashMap<>();
        userMap.put("userId",one.getId());
        String token = AppJwtUtil.getToken(userMap);
//        存入token和user
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);

        one.setPassword(null);
        one.setSalt(null);
        one.setPhone(null);
        map.put("user",one);
        return ResponseResult.okResult(map);
    }
}
